package tests

import (
	"context"
	"errors"
	"fmt"
	redislock "gitee.com/worklz/go-redis-lock"
	"github.com/go-redis/redis/v8"
	"log"
	"sync"
)

// 初始化Redis锁
func init() {
	err := redislock.Init(
		func(ctx context.Context, args ...interface{}) (interface{}, error) {
			res, err := GetRedisClient().Do(ctx, args...).Result()
			if err != nil && errors.Is(err, redis.Nil) {
				err = nil
			}
			return res, err
		},
		redislock.WithLogger(&MyLogger{}),
		redislock.WithFullKey(func(key string) string {
			return "redis.lock.example:" + key
		}),
	)
	if err != nil {
		panic(fmt.Sprintf("Redis锁初始化失败: %v", err))
	}
}

var redisClientOnce sync.Once
var redisClient *redis.Client

// GetRedisClient 获取Redis客户端
func GetRedisClient() *redis.Client {
	redisClientOnce.Do(func() {
		redisClient = redis.NewClient(&redis.Options{
			Addr:     "192.168.88.201:6379",
			Password: "123456", // 没有密码
			DB:       1,        // 默认DB
		})

		// 检查Redis连接
		ctx := context.Background()
		_, err := redisClient.Ping(ctx).Result()
		if err != nil {
			panic(fmt.Sprintf("Failed to connect to Redis: %v", err))
		}
	})
	return redisClient
}

// MyLogger 自定义日志实现
type MyLogger struct{}

func (m *MyLogger) Infof(format string, args ...interface{}) {
	log.Printf("[INFO] "+format+"\r\n", args...)
}

func (m *MyLogger) Warnf(format string, args ...interface{}) {
	log.Printf("[WARN] "+format+"\r\n", args...)
}

func (m *MyLogger) Errorf(format string, args ...interface{}) {
	log.Printf("[ERROR] "+format+"\r\n", args...)
}

// 测试使用的key
var key = "order:111"
